package queries;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * Class that represents a query 
 * 
 * @author Vika
 * @author ak2765
 */
public final class Query {
	
	public static final Query[] EMPTY_QUERY = new Query[0];
	
	private final List<String> keywords;

	public Query(String keywords) {
		StringTokenizer st = new StringTokenizer(keywords, " ");
		this.keywords = new ArrayList<String>();
		while(st.hasMoreTokens()){
		  this.keywords.add(st.nextToken());
		}
	}
	
	public Query(String... keywords) {
		this.keywords = new ArrayList<String>(Arrays.asList(keywords));
	}

	public List<String> getListOfWords() {
		return keywords;
	}

	/**
	 * @return
	 */
	public String nativeStringQuery() {
		StringBuilder buff = new StringBuilder(this.keywords.get(0));
		for(int i=1;i<this.keywords.size();i++) {
			buff.append(" ").append(this.keywords.get(i));
		}
		return buff.toString();
	}

	/**
	 * Append new keywords to query
	 * 
	 * @param keyWordsToAdd
	 * @return
	 */
	public Query addNewKeywords(List<String> keyWordsToAdd) {
		List<String> keywords = new LinkedList<String>(this.keywords);
		keywords.addAll(keyWordsToAdd);
		
		return new Query(keywords.toArray(new String[keywords.size()]));
	}
	
	@Override
	public String toString() {
		StringBuilder buff = new StringBuilder();
		buff.append("Query keywords:[");
		for (String word : this.keywords) {
			buff.append(" ").append(word);
		}
		buff.append(" ]");
		return buff.toString();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((keywords == null) ? 0 : keywords.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		
		Query other = (Query) obj;
		
		if (keywords == null) {
			if (other.keywords != null) {
				return false;
			}
		} else if (!keywords.equals(other.keywords)) {
			return false;
		}
		return true;
	}

}
